/**
 * 
 */
package edu.arizona.bio5.onto.decomposition.persistent.rdf;

import java.util.Set;

import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.semanticweb.owlapi.model.OWLEntity;

import edu.arizona.bio5.onto.decomposition.Atom;
import edu.arizona.bio5.onto.decomposition.MSSLabel;
import edu.arizona.bio5.onto.decomposition.persistent.ADPersistenceException;
import edu.arizona.bio5.onto.decomposition.persistent.LabelPersister;

/**
 * @author Pavel Klinov
 *
 */
public class SesameMSSLabelPersister extends SesameAbstractPersister implements LabelPersister {

	SesameMSSLabelPersister(RepositoryConnection conn) {
		super(conn);
	}
	
	
	@Override
	public void persist(Atom atom) throws ADPersistenceException {
		MSSLabel mssLabel = (MSSLabel) atom.getLabel(MSSLabel.TYPE);
		
		if (mssLabel == null || mssLabel.getSeedSignatures().isEmpty()) {
			return;
		}
		
		ValueFactory factory = getValueFactory();
		RepositoryConnection conn = getConnection();
		URI hasLabel = factory.createURI(RDFADConstants.AD_ATOM_HAS_LABEL);
		URI labelInstance = factory.createURI(RDFADConstants.AD_LABEL_INSTANCE + "_" + MSSLabel.TYPE + "_" + atom.getID().toString());
		URI labelType = factory.createURI(RDFADConstants.AD_LABEL_MSS);
		URI hasSignature = factory.createURI(RDFADConstants.AD_LABEL_HAS_SIGNATURE);
		URI hasTerm = factory.createURI(RDFADConstants.AD_SIGNATURE_HAS_TERM);
		int mssIndex = 0;
		
		try {
			conn.add(SesameOWLRDFUtils.getAtomURI(atom, factory), hasLabel, labelInstance, getNamedGraph());
			conn.add(labelInstance, RDF.TYPE, labelType, getNamedGraph());
					
			for (Set<OWLEntity> mss : mssLabel.getSeedSignatures()) {
				//need to generate URI for the signature
				URI mssNode = factory.createURI(RDFADConstants.AD_SIGNATURE_INSTANCE + atom.getID().toString() + "_" + mssIndex);
				
				mssIndex++;
				conn.add(labelInstance, hasSignature, mssNode, getNamedGraph());
				//now serialize the signature
				for (OWLEntity term : mss) {
					URI termURI = factory.createURI(SesameOWLRDFUtils.termToURI(term));
					
					conn.add(mssNode, hasTerm, termURI, getNamedGraph());
				}
			}
		} catch (RepositoryException e) {
			throw new ADPersistenceException(e);
		}
	}
}